use criterion::{black_box, criterion_group, criterion_main, Criterion, BenchmarkId};
use cdb::sql::execution::*;
use cdb::sql::Value;
use cdb::storage::page::PageManager;
use std::sync::Arc;

/// 基准测试：执行元组操作性能
fn benchmark_execution_tuple(c: &mut Criterion) {
    // 元组创建性能
    c.bench_function("tuple_creation", |b| {
        b.iter(|| {
            let values = vec![
                Value::Integer(black_box(42)),
                Value::Text(black_box("test_string".to_string())),
                Value::Boolean(black_box(true)),
                Value::Real(black_box(3.14)),
            ];
            ExecutionTuple::new(values)
        })
    });
    
    // 元组值访问性能
    c.bench_function("tuple_value_access", |b| {
        let values = vec![
            Value::Integer(42),
            Value::Text("test_string".to_string()),
            Value::Boolean(true),
            Value::Real(3.14),
        ];
        let tuple = ExecutionTuple::new(values);
        
        b.iter(|| {
            for i in 0..4 {
                let value = tuple.get_value(black_box(i)).unwrap();
                black_box(value);
            }
        })
    });
    
    // MVCC可见性检查性能
    c.bench_function("mvcc_visibility_check", |b| {
        let values = vec![Value::Integer(1)];
        let version_info = VersionInfo {
            xmin: 100,
            xmax: Some(200),
            committed: true,
        };
        let tuple = ExecutionTuple::with_version(values, version_info);
        
        b.iter(|| {
            for tx_id in 90..210 {
                let visible = tuple.is_visible_to_transaction(black_box(tx_id));
                black_box(visible);
            }
        })
    });
}

/// 基准测试：执行模式操作性能
fn benchmark_execution_schema(c: &mut Criterion) {
    // 模式创建性能
    c.bench_function("schema_creation", |b| {
        b.iter(|| {
            let columns = vec![
                ColumnInfo::new("id".to_string(), DataType::Integer, false),
                ColumnInfo::new("name".to_string(), DataType::String, true),
                ColumnInfo::new("age".to_string(), DataType::Integer, true),
                ColumnInfo::new("email".to_string(), DataType::String, true),
                ColumnInfo::new("active".to_string(), DataType::Boolean, false),
            ];
            ExecutionSchema::new(columns)
        })
    });
    
    // 列查找性能
    c.bench_function("column_lookup", |b| {
        let columns = vec![
            ColumnInfo::new("id".to_string(), DataType::Integer, false),
            ColumnInfo::new("name".to_string(), DataType::String, true),
            ColumnInfo::new("age".to_string(), DataType::Integer, true),
            ColumnInfo::new("email".to_string(), DataType::String, true),
            ColumnInfo::new("active".to_string(), DataType::Boolean, false),
        ];
        let schema = ExecutionSchema::new(columns);
        
        b.iter(|| {
            let index = schema.find_column_index(black_box("email"));
            black_box(index);
        })
    });
    
    // 模式投影性能
    c.bench_function("schema_projection", |b| {
        let columns = (0..20).map(|i| {
            ColumnInfo::new(format!("col_{}", i), DataType::Integer, false)
        }).collect();
        let schema = ExecutionSchema::new(columns);
        
        b.iter(|| {
            let projection_indices = vec![0, 2, 4, 6, 8];
            let projected = schema.project(black_box(&projection_indices)).unwrap();
            black_box(projected);
        })
    });
    
    // 模式合并性能
    c.bench_function("schema_merge", |b| {
        let left_columns = (0..10).map(|i| {
            ColumnInfo::new(format!("left_{}", i), DataType::Integer, false)
        }).collect();
        let right_columns = (0..10).map(|i| {
            ColumnInfo::new(format!("right_{}", i), DataType::String, true)
        }).collect();
        
        let left_schema = ExecutionSchema::new(left_columns);
        let right_schema = ExecutionSchema::new(right_columns);
        
        b.iter(|| {
            let merged = left_schema.merge(black_box(&right_schema));
            black_box(merged);
        })
    });
}

/// 基准测试：执行上下文性能
fn benchmark_execution_context(c: &mut Criterion) {
    // 内存分配性能
    c.bench_function("memory_allocation", |b| {
        let page_manager = Arc::new(PageManager::new(1000));
        let mut context = ExecutionContext::new(page_manager, 123);
        
        b.iter(|| {
            let size = black_box(1024);
            context.allocate_memory(size).unwrap();
            context.deallocate_memory(size);
        })
    });
    
    // 表元数据访问性能
    c.bench_function("table_metadata_access", |b| {
        let page_manager = Arc::new(PageManager::new(1000));
        let mut context = ExecutionContext::new(page_manager, 123);
        
        // 添加一些表元数据
        for i in 0..100 {
            let columns = vec![
                ColumnInfo::new("id".to_string(), DataType::Integer, false),
                ColumnInfo::new("name".to_string(), DataType::String, true),
            ];
            let schema = ExecutionSchema::new(columns);
            let metadata = TableMetadata::new(format!("table_{}", i), schema);
            context.add_table_metadata(metadata);
        }
        
        b.iter(|| {
            let table_name = format!("table_{}", black_box(50));
            let metadata = context.get_table_metadata(&table_name);
            black_box(metadata);
        })
    });
}

/// 基准测试：批处理操作性能
fn benchmark_execution_batch(c: &mut Criterion) {
    let mut group = c.benchmark_group("batch_operations");
    
    // 测试不同批次大小的性能
    for batch_size in [10, 100, 1000].iter() {
        group.bench_with_input(
            BenchmarkId::new("batch_creation", batch_size),
            batch_size,
            |b, &size| {
                let columns = vec![
                    ColumnInfo::new("id".to_string(), DataType::Integer, false),
                    ColumnInfo::new("value".to_string(), DataType::String, true),
                ];
                let schema = ExecutionSchema::new(columns);
                
                b.iter(|| {
                    let tuples: Vec<ExecutionTuple> = (0..size).map(|i| {
                        ExecutionTuple::new(vec![
                            Value::Integer(i as i64),
                            Value::String(format!("value_{}", i)),
                        ])
                    }).collect();
                    
                    let batch = ExecutionBatch::new(tuples, schema.clone());
                    black_box(batch);
                })
            },
        );
    }
    
    // 批次过滤性能
    for batch_size in [100, 1000].iter() {
        group.bench_with_input(
            BenchmarkId::new("batch_filter", batch_size),
            batch_size,
            |b, &size| {
                let columns = vec![
                    ColumnInfo::new("id".to_string(), DataType::Integer, false),
                    ColumnInfo::new("value".to_string(), DataType::String, true),
                ];
                let schema = ExecutionSchema::new(columns);
                
                let tuples: Vec<ExecutionTuple> = (0..size).map(|i| {
                    ExecutionTuple::new(vec![
                        Value::Integer(i as i64),
                        Value::String(format!("value_{}", i)),
                    ])
                }).collect();
                
                let batch = ExecutionBatch::new(tuples, schema);
                
                b.iter(|| {
                    let filtered = batch.filter(|tuple| {
                        if let Ok(Value::Integer(id)) = tuple.get_value(0) {
                            *id % 2 == 0
                        } else {
                            false
                        }
                    });
                    black_box(filtered);
                })
            },
        );
    }
    
    // 批次投影性能
    for batch_size in [100, 1000].iter() {
        group.bench_with_input(
            BenchmarkId::new("batch_projection", batch_size),
            batch_size,
            |b, &size| {
                let columns = vec![
                    ColumnInfo::new("id".to_string(), DataType::Integer, false),
                    ColumnInfo::new("name".to_string(), DataType::String, true),
                    ColumnInfo::new("age".to_string(), DataType::Integer, true),
                    ColumnInfo::new("email".to_string(), DataType::String, true),
                ];
                let schema = ExecutionSchema::new(columns);
                
                let tuples: Vec<ExecutionTuple> = (0..size).map(|i| {
                    ExecutionTuple::new(vec![
                        Value::Integer(i as i64),
                        Value::String(format!("name_{}", i)),
                        Value::Integer((i % 100) as i64),
                        Value::String(format!("email_{}@test.com", i)),
                    ])
                }).collect();
                
                let batch = ExecutionBatch::new(tuples, schema);
                
                b.iter(|| {
                    let projected = batch.project(black_box(&[0, 2])).unwrap();
                    black_box(projected);
                })
            },
        );
    }
    
    group.finish();
}

/// 基准测试：统计信息性能
fn benchmark_statistics(c: &mut Criterion) {
    // 算子统计信息更新性能
    c.bench_function("operator_statistics_update", |b| {
        let mut stats = OperatorStatistics::default();
        
        b.iter(|| {
            stats.tuples_processed += black_box(1);
            stats.tuples_output += black_box(1);
            stats.execution_time_us += black_box(100);
            stats.memory_usage_bytes += black_box(64);
        })
    });
    
    // 执行统计信息聚合性能
    c.bench_function("execution_statistics_aggregation", |b| {
        let mut execution_stats = ExecutionStatistics::default();
        
        // 添加多个算子的统计信息
        for i in 0..100 {
            let mut op_stats = OperatorStatistics::default();
            op_stats.tuples_processed = i * 10;
            op_stats.tuples_output = i * 8;
            op_stats.execution_time_us = i * 1000;
            
            execution_stats.operator_stats.insert(format!("operator_{}", i), op_stats);
        }
        
        b.iter(|| {
            let total_processed = execution_stats.total_tuples_processed();
            let total_output = execution_stats.total_tuples_output();
            let selectivity = execution_stats.selectivity();
            let slowest = execution_stats.slowest_operator();
            
            black_box((total_processed, total_output, selectivity, slowest));
        })
    });
}

criterion_group!(
    benches,
    benchmark_execution_tuple,
    benchmark_execution_schema,
    benchmark_execution_context,
    benchmark_execution_batch,
    benchmark_statistics
);
criterion_main!(benches);
